import { defineStore } from 'pinia';
import storage from '../../commons/storage';
import { isEmpty, isNotEmpty, cloneDeep } from '../../commons/utils';

export default defineStore('useAuthStore', {
    state: () => {
        return {
            collapse: false,
            tenant: '',
            tenantModuleList: [],
            shopList: [],
            shopId: '',
            moduleCode: '',
            menus: [],
            noButMenuList: [],
            permissions: new Set()
        };
    },
    actions: {
        setAuth(zwauth, zwcode) {
            this.tenant = zwauth.tenant;
            if (isEmpty(this.tenantModuleList)) {
                this.tenantModuleList = zwauth.tenantModuleList;
            }
            this.shopList = zwauth.shopList;
            this.shopId = storage.get('ZW-SHOPID');
            this.moduleCode = zwcode;
            this.menus = zwauth.menuList.filter(item => {
                return item.code === zwcode;
            })[0];
            if (isNotEmpty(this.menus)) {
                const getPermissions = list => {
                    if (isEmpty(list)) return;
                    list.forEach(item => {
                        if (item.type !== 4) {
                            const deepList = cloneDeep(item.list);
                            delete cloneDeep(item).list;
                            this.noButMenuList.push(item);
                            getPermissions(deepList);
                        } else {
                            if (isNotEmpty(item.code)) {
                                this.permissions.add(item.code);
                            }
                        }
                    });
                };
                getPermissions(this.menus.list);
            }
        },
        clear() {
            this.collapse = false;
            this.tenant = '';
            this.tenantModuleList.length = 0;
            this.shopList.length = 0;
            this.shopId = '';
            this.moduleCode = '';
            this.menus.length = 0;
            this.noButMenuList.length = 0;
            this.permissions.clear();
        }
    }
});
